package com.example.demoexample.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * 折线统计图
 */
public class PolylineGraph extends View {
    //View自身的宽和高
    private int mHeight;
    private int mWidth;

    private int DEFAULT_WIDTH;
    private int DEFAULT_HEIGHT;
    //-------------统计图相关-------------
    //x轴的条目
    private int xNum = 8;
    //y轴的条目
    private int yNum = 5;

    private int ySize;
    private int xSize;
    private int startWidth;
    private int startHeight;
    //-------------必须给的资源相关-------------
    private String[] xStr = new String[]{"0", "3", "6", "9", "12", "15", "18", "21"};
    private String[] yStr = new String[]{"50%", "MAX"};
    private int[] yValue = new int[]{8, 15, 33, 48, 77, 80, 95};
    private int yMaxHeight; //坐标高度
    private int max = 0;
//    private String[] yStr = new String[]{"0", "3", "6", "9", "12", "15", "18","21"};

    //边框的画笔
    private Paint borderPaint;
    //文字的画笔
    private Paint textPaint;
    //折线的画笔
    private Paint linePaint;
    //黑点的画笔
    private Paint pointPaint;

    //-------------颜色相关-------------
    //边框颜色
    private int mColor = 0xFF888888;
    //文字颜色
    private int textColor = 0xFF888888;
    //折线颜色
    private int lineColor = 0xFF000000;
    //黑点颜色
    private int pointColor = 0xFF000000;

    public PolylineGraph(Context context) {
        this(context, null);
    }

    public PolylineGraph(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public PolylineGraph(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        ySize = dpToPx(20);
        xSize = dpToPx(40);
        startWidth = dpToPx(10);
        startHeight = dpToPx(10);

        DEFAULT_WIDTH = dpToPx(320);
        DEFAULT_HEIGHT = dpToPx(120);
        getMax();
        yMaxHeight = (yNum - 1) * ySize + startHeight;

        initPaint();
    }

    /**
     * 获取最大值
     */
    private void getMax(){
        for (int i =0; i< yValue.length;i++){
            if (max < yValue[i]){
                max = yValue[i];
            }
        }
    }

    private void initPaint() {
        //边框画笔
        borderPaint = new Paint();
        borderPaint.setAntiAlias(true);
        borderPaint.setStyle(Paint.Style.STROKE);
        borderPaint.setColor(Color.GREEN);
        borderPaint.setStrokeWidth(1);

        //文字画笔
        textPaint = new Paint();
        textPaint.setTextSize(30);
        textPaint.setColor(textColor);
        textPaint.setAntiAlias(true);

        //区域画笔
        linePaint = new Paint();
        linePaint.setColor(lineColor);
        linePaint.setAntiAlias(true);
        linePaint.setStyle(Paint.Style.STROKE);
        linePaint.setStrokeWidth(2);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        int widthMode = MeasureSpec.getMode(widthMeasureSpec);   //获取宽的模式
//        int heightMode = MeasureSpec.getMode(heightMeasureSpec); //获取高的模式
//        int widthSize = MeasureSpec.getSize(widthMeasureSpec);   //获取宽的尺寸
//        int heightSize = MeasureSpec.getSize(heightMeasureSpec); //获取高的尺寸
//
//        if (widthMode == MeasureSpec.AT_MOST
//                && heightMode == MeasureSpec.AT_MOST) {
//            setMeasuredDimension(widthMeasureSpec, DEFAULT_HEIGHT);
//        } else if (widthMode == MeasureSpec.AT_MOST) {
//            setMeasuredDimension(widthMeasureSpec, heightSize);
//        } else if (heightMode == MeasureSpec.AT_MOST) {
//            setMeasuredDimension(widthSize, DEFAULT_HEIGHT);
//        }

        int widthResult = 0;
        //view根据xml中layout_width和layout_height测量出对应的宽度和高度值，
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        switch (widthSpecMode){
            case MeasureSpec.UNSPECIFIED:
                widthResult = widthSpecSize;
                break;
            case MeasureSpec.AT_MOST://wrap_content时候
                widthResult = DEFAULT_WIDTH;
                break;
            case MeasureSpec.EXACTLY:
                //当xml布局中是准确的值，比如200dp是，判断一下当前view的宽度和准确值,取两个中大的，这样的好处是当view的宽度本事超过准确值不会出界
                //其实可以直接使用准确值
                widthResult = Math.max(DEFAULT_WIDTH, widthSpecSize);
                break;
        }

        int heightResult = 0;
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        switch (heightSpecMode){
            case MeasureSpec.UNSPECIFIED:
                heightResult = heightSpecSize;
                break;
            case MeasureSpec.AT_MOST://wrap_content时候
                heightResult = DEFAULT_HEIGHT;
                break;
            case MeasureSpec.EXACTLY:
                heightResult = Math.max(DEFAULT_HEIGHT, heightSpecSize);
                break;
        }
        setMeasuredDimension(widthResult, heightResult);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        drawBorder(canvas);
        drawText(canvas);

        drawLine(canvas);
//        canvas.drawLine(0,mHeight - ySize,mWidth,mHeight - ySize,borderPaint);
//        Path path = new Path();
//        path.lineTo(dpToPx(10), mHeight);
//        path.moveTo(dpToPx(10),dpToPx(10));
//        path.lineTo(mWidth, dpToPx(10));
//        canvas.drawPath(path,borderPaint);
    }

    /**
     * 画边框
     *
     * @param canvas
     */
    private void drawBorder(Canvas canvas) {
        Path path = new Path();
        //循环水平的线
        for (int i = 0; i < yNum; i++) {
            path.moveTo(startWidth, startHeight + i * ySize);
            path.lineTo(startWidth + (xNum - 1) * xSize, i * ySize+startHeight);
            canvas.drawPath(path, borderPaint);
        }
        //循环垂直的线
        for (int j = 0; j < xNum; j++) {
            path.moveTo(startWidth + j * xSize, startHeight);
            path.lineTo(startWidth + j * xSize, (yNum - 1) * ySize+startHeight);
            canvas.drawPath(path, borderPaint);
        }

    }

    /**
     * 画文字
     *
     * @param canvas
     */
    private void drawText(Canvas canvas) {
        //事先说明：文字排版为了好看，这里的20，都为20px的边距
        //x轴的文字
        for (int i = 0; i < xStr.length; i++) {
            //测量文字的宽高
            Rect rect = new Rect();
            textPaint.getTextBounds(xStr[i], 0, xStr[i].length(), rect);
            float textWidth = rect.width();
            float textHeight = rect.height();
            canvas.drawText(xStr[i], startWidth + i * xSize - textWidth / 2, textHeight + 20 + (yNum - 1) * ySize+startHeight, textPaint);
        }
        //y轴的文字
        //测量文字的宽高
        Rect rect = new Rect();
        textPaint.getTextBounds(yStr[0], 0, yStr[0].length(), rect);
        float textWidth = rect.width();
        float textHeight = rect.height();
        canvas.drawText(yStr[0], startWidth + 7 * xSize + 20, 2 * ySize + (textHeight / 2)+startHeight, textPaint);

        Rect rect2 = new Rect();
        textPaint.getTextBounds(yStr[1], 0, yStr[1].length(), rect);
        float textWidth2 = rect2.width();
        float textHeight2 = rect2.height();
        canvas.drawText(yStr[1], startWidth + 7 * xSize + 20, textHeight2 / 2 + 10+startHeight, textPaint);

    }

    /**
     * 画折线
     * @param canvas
     */
    private void drawLine(Canvas canvas) {
        Path path = new Path();
        for (int i = 0; i < yValue.length; i++) {
            //计算折线的位置：（当前点的值/最大值）拿到百分比percent
            //用百分比percent乘与y轴总长，就获得了折线的位置
            //这里拿到的百分比一直为0，所以换一种方法，先乘与总长再除与最大值，而且记得加上负号
            if (max == 0){
                return;
            }
            float position = yMaxHeight - yValue[i] * (yMaxHeight-startHeight) /max;
//            float position = -(yValue[i] * yLastSize / yMaxValue);
            if (i == 0) {
                //第一个点需要移动
                path.moveTo(startWidth + i * xSize, position);
            } else {
                //其余的点直接画线
                path.lineTo(startWidth + i * xSize, position);
            }
            canvas.drawPath(path, linePaint);
        }
    }

    private int dpToPx(int dp) {
        return (int) (dp * getContext().getResources().getDisplayMetrics().density);
    }

}
